package processor

import (
	"os"
	"os/exec"
)

// RestartApplication 重启应用
func (cls *Processor) RestartApplication(name string) error {
	cls.mutex.RLock()
	defer cls.mutex.RUnlock()

	if application, ok := cls.application[name]; ok {
		if StateStarted != application.state {
			return nil
		}

		if err := cls.restart(application); nil != err {
			return err
		}
	}

	return nil
}

func (cls *Processor) restart(application *Application) error {
	application.state = StateRestarting
	application.callback(StateRestarting, nil)
	if err := application.c.Process.Signal(os.Interrupt); nil != err {
		return err
	}

	var c = exec.Command(application.command, application.args...)
	c.Dir = application.working
	c.Env = application.environments
	c.Stdout = application.output
	c.Stderr = application.output

	application.c = c

	// 启动
	if err := c.Start(); nil != err {
		application.state = StateStartFailed
		application.callback(StateStartFailed, err)

		return err
	}

	application.pid = int32(c.Process.Pid)
	application.state = StateStarted
	application.callback(StateStarted, nil)

	return nil
}
